package com.tony.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreThread {
    private int a = 0;
    class Bank{
        private int acount=0;

        public void save(int money){
            acount+=money;
        }

        public int getAcount() {
            return acount;
        }

        public void setAcount(int acount) {
            this.acount = acount;
        }
    }
    class SaveMoney implements Runnable{
        private Bank bank;
        private Semaphore semaphore;

        public SaveMoney(Bank bank,Semaphore semaphore){
            this.bank =bank;
            this.semaphore = semaphore;
        }
        @Override
        public void run() {
            int b=a++;
            if(semaphore.availablePermits()>0){
                System.out.println("线程："+b+"启动，进入银行，有位置存款");
            }else{
                System.out.println("线程："+b+"启动，进入银行，无位置，去排队");
            }
            try{
                semaphore.acquire();
                bank.save(10);
                System.out.println(b+"账户余额为："+bank.getAcount());
                Thread.sleep(1000);
                System.out.println("线程" + b + "存钱完毕，离开银行");
                semaphore.release();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    void userSaveMoney(){
        Bank bank = new Bank();
        Semaphore semaphore = new Semaphore(2);
        ExecutorService es = Executors.newCachedThreadPool();
        for(int j=0;j<20;j++){
            es.submit(new Thread(new SaveMoney(bank,semaphore)));
        }
        es.shutdown();
        semaphore.acquireUninterruptibly(2);
        System.out.println("到点了，工作人员要吃饭了");
        // 释放两个许可，并将其返回给信号量
        semaphore.release(2);
    }

    public static void main(String[] args) {
        SemaphoreThread semaphoreThread = new SemaphoreThread();
        semaphoreThread.userSaveMoney();
    }
}
